<?php

require_once( '../../libs/smarty.inc' );

require_once( '../../libs/Class_DB.php' );

require_once( '../../libs/Class_ERROR.php' );

require_once( '../../libs/login.inc.php' );

require_once( '../../libs/const.php' );



if( !in_array( "A", $_SESSION['ADMIN_LOGIN']['AUTH_CD'] ) ) exit;



$db = new Class_DB;



if( $_SERVER['REQUEST_METHOD'] == 'GET' ){

	

	$phase = 'input';

	

	if( isset($_GET['id']) && $_GET['id'] != '' ){

		

		if( is_numeric( $_GET['id'] ) ){

			

			$sql = sprintf("SELECT * FROM M_PRODUCTS WHERE id = %u", $_GET['id'] );

			$res = $db->query( $sql );

			$forms = mysql_fetch_array( $res, MYSQL_ASSOC );



		}

		

	}else{

		$forms['id'] = '';

		$forms['category'] = 1;

	}



}else{

	

	$forms = $_POST;

	

	// 入力画面から

	if( $forms['mode'] == 'input' ){

		$err = new Class_ERROR;

		

		$err_mes['pro_name']	= $err->check( $forms['pro_name'], array("EXIST") );

		$err_mes['unit']	= $err->check( $forms['unit'], array("EXIST") );

		$err_mes['cost']	= $err->check( $forms['cost'], array("EXIST", "NUM") );



		if( $err->clear ){

			

			if( $forms['id'] == '' ){

				//新規登録

				$sql = sprintf( "INSERT INTO M_PRODUCTS(category, pro_name, unit, cost, r_date, u_date) VALUES( %u, '%s', '%s', %u, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP )",

					$forms['category'],

					$db->quote( $forms['pro_name'] ),

					$db->quote( $forms['unit'] ),

					$forms['cost']

				);

				$db->query( $sql );

				

				$message = '登録が完了しました。';

			}else{

				//更新

				$sql = sprintf( "UPDATE M_PRODUCTS SET category = %u, pro_name = '%s', unit = '%s', cost = %u, u_date = CURRENT_TIMESTAMP WHERE id = %u",

					$forms['category'],

					$db->quote( $forms['pro_name'] ),

					$db->quote( $forms['unit'] ),

					$forms['cost'],

					$forms['id']

				);

				$db->query( $sql );



				$message = '更新が完了しました。';

			}

			

			

			

			

			$phase = 'complete';

		}else{

			$phase = 'input';

		}



	}



	if( $forms['mode'] == 'delete' ){

		$sql = sprintf( "DELETE FROM M_PRODUCTS WHERE id = %u", $forms['id'] );

		$db->query( $sql );

		$message = '削除が完了しました。';

		$phase = 'complete';

	}





}



if( $phase == 'input' ){

	if( $forms['id'] == ''){

		$message = '内容を確認し、登録ボタンをクリックしてください。';

	}else{

		$message = '内容を確認し、更新ボタンをクリックしてください。';

	}

}



$category[5] = '製品';

$smarty->assign('message', $message);

$smarty->assign('phase', $phase);

$smarty->assign('category', $category );

if( isset( $forms ) ) $smarty->assign('forms', $forms);

if( isset( $err_mes ) ) $smarty->assign('err', $err_mes);



$smarty->display('web-admin/products_form.html');





?>